<?php


header("Content-type: text/html; charset=utf-8");

// 全局常量   开发者自定义token  长度3-32
define("TOKEN","cookee");

//服务号的信息 
define("ID","wxf283b097a3fbf3d9");
define("SECRET","4e6d3b1246ff98145702321a343cf93c");


// 实例化对象
$wechatObj = new wechatCallbackapiTest();

// 主路径跳转
if (isset($_GET['echostr'])) {

    //微信服务器验证响应
    $wechatObj->valid();
}else{
    // 微信消息响应
    $wechatObj->setToken();
    $wechatObj->responseMsg();
}



// 公众号接口类
class wechatCallbackapiTest
{
    public $access_token;
    public $save_time;
    // 构造函数,初始化token
    public function __construct()
    {
        $this->getToken();
    } 

    // 模拟发送post请求
    public function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 设置access_token
    public function setToken(){

            $new_time=time();
            $time=$new_time - $this->save_time;
            if($time>=7200){
                 $this->getToken();
            }        

    }
    
    // 获取token
    public function getToken(){
          $ch = curl_init();
          $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.ID.'&secret='.SECRET;
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//禁止直接显示获取的内容 重要
          curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //
          curl_setopt($ch, CURLOPT_HEADER, 0);
          $this->access_token=json_decode(curl_exec($ch))->access_token;
          $this->save_time=time(); 

    }



    // 微信服务器验证
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

     // 字符串验证
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    // 微信服务器响应响应
    public function responseMsg()
    {   

        // 接收微信推送的xml
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        // xml有效
        if (!empty($postStr)){

            // 将xml解析为一个对象
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            
            //判断事件类型
            $msgType = $postObj->MsgType;
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();
            // 消息分类
            switch($msgType){

                //多客服消息 
                case "text":
                      $textTpl = "<xml>
                                      <ToUserName><![CDATA[%s]]></ToUserName>
                                      <FromUserName><![CDATA[%s]]></FromUserName>
                                      <CreateTime>%s</CreateTime>
                                      <MsgType><![CDATA[%s]]></MsgType>
                                  </xml>";
                      $msgType="transfer_customer_service";
                      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);
                      echo $resultStr;
                      break;

                // 事件消息
                case "event":
                      $event=$postObj->Event;
                      switch($event){
                          // 用户关注帐号事件推送
                          case "subscribe":
                              $textTpl = "<xml>
                                          <ToUserName><![CDATA[%s]]></ToUserName>
                                          <FromUserName><![CDATA[%s]]></FromUserName>
                                          <CreateTime>%s</CreateTime>
                                          <MsgType><![CDATA[%s]]></MsgType>
                                          <Content><![CDATA[%s]]></Content>
                                          </xml>";
                              $msgType = "text";
                              $contentStr="hello,欢迎关注曲奇单车,新奇好玩,应有尽有,么么哒~~";
                              $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                              echo $resultStr;
                              break;

                          // 用户单击菜单事件推送
                          case "CLICK":
                              $key=$postObj->EventKey;                                                                      
                              switch($key){
                                    // wifi设置
                                    case "WIFI":
                                        $textTpl = "<xml>
                                                    <ToUserName><![CDATA[%s]]></ToUserName>
                                                    <FromUserName><![CDATA[%s]]></FromUserName>
                                                    <CreateTime>%s</CreateTime>
                                                    <MsgType><![CDATA[%s]]></MsgType>
                                                    <Content><![CDATA[%s]]></Content>
                                                    </xml>";
                                        $msgType = "text";
                                        $contentStr="WIFI正在接入中,请耐心等待";
                                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                                        echo $resultStr;    
                                        break; 
                                    // 导航
                                    case "NAVIGATION":
                                        $textTpl = "<xml>
                                                    <ToUserName><![CDATA[%s]]></ToUserName>
                                                    <FromUserName><![CDATA[%s]]></FromUserName>
                                                    <CreateTime>%s</CreateTime>
                                                    <MsgType><![CDATA[%s]]></MsgType>
                                                    <Content><![CDATA[%s]]></Content>
                                                    </xml>";
                                        $msgType = "text";
                                        $contentStr="导航功能正在接入,请耐心等待";
                                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                                        echo $resultStr;
                                        break;
                                    default :
                                        echo "";
                                        break;
                              }
                              // 菜单命令结束
                              break;
                          // 默认
                          default :
                              echo "";
                              break;
                      }
                      break;
                
                // 设备事件
                case "device_event":
                    file_put_contents("mylog.log","接收到设备事件\r\n",FILE_APPEND);
                    $event=$postObj->Event;
                    $deviceType=$postObj->DeviceType;
                    $deviceID=$postObj->DeviceID;
                    $sessionID=$postObj->SessionID;
                    $openID=$postObj->OpenID;
                    switch($event){
                        // 用户绑定设备事件推送
                        case "bind":
                          file_put_contents("mylog.log","接收到设备绑定事件\r\n",FILE_APPEND);
                          $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                          $data='{
                                   "touser":"o2eKTuM8aixX3LAKU5pJlbyzZGI0",
                                   "template_id":"sMRwmK6xACFcwt7fyCvX_8ka1-pf7ZWqaqDjWuKzZ-k",
                                   "url":"http://test.cookee.com.cn/html/bike/index.html#/status",
                                   "topcolor":"#FF0000",
                                   "data":{
                                             "first": {
                                                 "value":"恭喜你绑定成功啦",
                                                 "color":"#173177"
                                             },
                                             "keyword1":{
                                                 "value":"570869214@qq.com",
                                                 "color":"#173177"
                                             },
                                             "keyword2": {
                                                 "value":"这是我的绑定说明",
                                                 "color":"#333"
                                             },
                                             "remark":{
                                                 "value":"这里是下面的说明文字，随便写，颜色可以自定义",
                                                 "color":"#173177"
                                             }
                                          }  
                                  }';
                          $res = $this->https_request($url, $data);
                          return json_decond($res,true);
                          file_put_contents("mylog.log",$res."\r\n",FILE_APPEND);
                          break; 
                        // 用户解绑设备事件推送
                        case "unbind":
                          $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                          $data='{
                              "touser":"'.$openID.'",
                                     "template_id":"sMRwmK6xACFcwt7fyCvX_8ka1-pf7ZWqaqDjWuKzZ-k",
                                     "url":"http://test.cookee.com.cn/html/bike/index.html#/status",
                                     "topcolor":"#FF0000",
                                     "data":{
                                             "first": {
                                                 "value":"恭喜你解绑了",
                                                 "color":"#173177"
                                             },
                                             "keyword1":{
                                                 "value":"570869214@qq.com",
                                                 "color":"#173177"
                                             },
                                             "keyword2": {
                                                 "value":"这是我的绑定说明",
                                                 "color":"#333"
                                             },
                                             "remark":{
                                                 "value":"这里是下面的说明文字，随便写，颜色可以自定义",
                                                 "color":"#173177"
                                             }
                                     }  
                          }';
                          $res = $this->https_request($url, $data);
                          return json_decond($res,true);
                          break; 
                    }
                    break;
                // 默认
                default :
                    echo "";
                    break;
            }


        // xml无效
        }else{
            echo "";
            exit;
        }
    }
}


?>